import React, { useState, useEffect } from "react";
import "./TicketView.css";

export default function TicketView() {
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("http://localhost:8080/api/tickets")
      .then((response) => {
        if (!response.ok) {
          throw new Error("获取售票数据失败");
        }
        return response.json();
      })
      .then((data) => {
        setTickets(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error">错误: {error}</div>;
  }

  return (
    <div className="ticket-view-container">
      <h1>卖票情况</h1>
      <div className="ticket-table-container">
        <table className="ticket-table">
          <thead>
            <tr>
              <th>票ID</th>
              <th>电影名称</th>
              <th>开始时间</th>
              <th>票价</th>
              <th>座位</th>
              <th>手机号</th>
              <th>购票时间</th>
            </tr>
          </thead>
          <tbody>
            {tickets.map((ticket) => (
              <tr key={ticket.id}>
                <td>{ticket.id}</td>
                <td>{ticket.schedule.movie.title}</td>
                <td>{new Date(ticket.schedule.start_time).toLocaleString()}</td>
                <td>{ticket.schedule.price.toFixed(2)}元</td>
                <td>
                  {ticket.rowNo}排{ticket.colNo}座
                </td>
                <td>{ticket.phone}</td>
                <td>{new Date(ticket.soldAt).toLocaleString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
